#!/usr/bin/env python
# coding: utf-8

import re
import os
import sys
import time
import codecs
import base64
import socket
import datetime
import cStringIO
import threading
import ConfigParser
import logging,logging.handlers
from optparse import OptionParser

from call_iso8583 import *
from call_xml import *

#变量
Path=os.getcwd() + "/file/"
Path_config=os.path.abspath('.') + "/config/"

#配置文件
config_file=Path_config + "config.cfg"

#日志文件
#Log_file_8583=os.path.abspath('.') + "/Check_Message.log"

#日志处理
def My_Logging():
    global logger2
    #打开日志文件
    try:
        fp = open( Log_file_8583, 'w' )
    except:
        sys.exit()
    #创建loger对象    
    logger2 = logging.getLogger()
    logger2.setLevel(logging.DEBUG)
    # 创建log递送员    
    fh = logging.FileHandler(Log_file_8583)
    #创建码货员
    #format = "%(asctime)s %(filename)s[line:%(lineno)d]%(message)s"
    #formater = logging.Formatter(format)
    #设置
    #fh.setFormatter(formater)
    #设置日志级别
    fh.setLevel(logging.DEBUG)
    logger2.addHandler(fh)

#解析配置文件
def config_paraser( section, option ):
    #创建解析器对象
    cf=ConfigParser.ConfigParser()
    #读取配置文件
    print("开始解析报文:%s" % config_file)
    cf.readfp(codecs.open(config_file,"r","utf-8-sig"))
    #获取数据
    ServerList = cf.get( section, option )
    ServerList = ServerList.encode("utf-8")
    return ServerList

#交易路由主函数
def trans_route_main( Buf, Server ):
    print("Req_Server...:%s" % Server)
    #解析配置报文
    try:
        Server_List_Xml = config_paraser( 'MESSAGE_TYPE', 'xml' )
        if ( len(Server_List_Xml) > 0):
            if ( Server in Server_List_Xml ):
                Trans_Flag = unpack_check_route_xml( Buf, Server )
                return Trans_Flag
        else:
            Server_List_8583 = config_paraser( 'MESSAGE_TYPE', '8583' )
            if ( len(Server_List_8583) > 0 ):
                print("请求报文类型8583...:%s" % Server)
                if ( Server in Server_List_8583 ):
                    Trans_Flag = unpack_check_route_8583( Buf, Server )
                    return Trans_Flag
        return False
    except:
        print("解析配置报文失败...")
        return False

if __name__ == '__main__':
    buf = "03120200F22244C188C1988402000000160000011762238453505426689460000000000010000063009352849539406300800011000608030900001203090000000122117480    204     37601          024000000010000000000000000156651047B6926A1E8B2000000000000000005ZF00402026370500    0309000008300008263705001762238453505426689110450005785165996398"
    Server = "10.3.8.15:8509"
    #调用交易路由主函数
    trans_route_main( buf, Server )
